#!/usr/bin/wish
#type “wish change_filenames.tcl” to run script

package require Tk

font create EmacDefaultFont -family Helvetica -size 16
option add *font EmacDefaultFont
ttk::style configure TFrame -font EmacDefaultFont ;#change TFrame style
ttk::style configure TButton -font EmacDefaultFont ;#change TButton style
ttk::style configure TCheckbutton -font EmacDefaultFont ;#change TCheckbutton style
ttk::style configure TLable -font EmacDefaultFont ;#change TLable style
ttk::style configure TEntry -font EmacDefaultFont ;#change TEntry style
ttk::style configure TRadiobutton -font EmacDefaultFont ;#change TRadiobutton style

global dirPath

wm title . "Change file names to lowercase"
frame .frame
grid .frame -row 0 -column 0

label .frame.lbl -text "path of directory:" -width 30
entry .frame.ent -textvariable dirPath -width 50
button .frame.btn1 -text "Change" -width 8 -command {change_name $dirPath 0}
button .frame.btn2 -text "Quit" -width 8 -command {exit}

grid .frame.lbl -row 0 -column 0
grid .frame.ent -row 0 -column 1 -columnspan 3 
grid .frame.btn1 -row 1 -column 2
grid .frame.btn2 -row 1 -column 3

proc change_name {dir_name level} {
    if {![file isdirectory $dir_name]} {
        return -code error "directory $dir_name not exists"
    }

    #set file_list [exec ls "$dir_name"] ;#file name not include path
    set file_list [glob -nocomplain -directory $dir_name *]

    foreach fl $file_list {
        set old_path_name $fl

        if {[file isdirectory $old_path_name]} {
            set sub_dir $old_path_name 
            change_name $sub_dir [expr $level + 1]
        } elseif {[file isfile $fl]} {
            set lower_name [string tolower [file tail $fl]]
            if {[string compare $lower_name [file tail $fl]]} {
                set lower_path_name [file join $dir_name $lower_name]
                exec mv  $old_path_name $lower_path_name
            }
        } else {
            puts "unknown file type: $fl"
        }
    }

    if {$level == 0} {
        tk_messageBox -message "All file names are changed to lowercase under directory: $dir_name !"
    } else {
        puts "All file names are changed to lowercase under subdirectory: $dir_name !"
    }

    return
}
